package com.sright.bcard.enterprise.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.sright.bcard.common.biz.manager.ContentCheckManager;
import com.sright.bcard.common.biz.manager.DingTalkManager;
import com.sright.bcard.common.service.share.dto.LoginUser;
import com.sright.bcard.common.service.share.dto.content.OpenAccountMessageDTO;
import com.sright.bcard.common.service.share.dto.page.PageParamRequest;
import com.sright.bcard.common.service.share.dto.pager.Pager;
import com.sright.bcard.common.service.share.dto.request.CreateAccountParam;
import com.sright.bcard.common.service.share.dto.user.RegisterDTO;
import com.sright.bcard.common.service.share.enums.SourceTypeEnum;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.DateTimeUtils;
import com.sright.bcard.content.dal.dao.*;
import com.sright.bcard.content.dal.entity.*;
import com.sright.bcard.content.dal.result.CardListDTO;
import com.sright.bcard.content.dal.result.EnterpriseMemberResult;
import com.sright.bcard.content.share.service.SmsService;
import com.sright.bcard.enterprise.biz.manager.EnterpriseManager;
import com.sright.bcard.enterprise.dal.dao.EnterpriseDAO;
import com.sright.bcard.enterprise.dal.entity.EnterpriseDO;
import com.sright.bcard.common.service.share.dto.enterprise.EnterpriseDTO;
import com.sright.bcard.common.service.share.dto.enterprise.EnterpriseMemberDTO;
import com.sright.bcard.enterprise.share.request.UpdateEnterpriseParam;
import com.sright.bcard.user.dal.dao.AdminDAO;
import com.sright.bcard.user.dal.dao.MemberDAO;
import com.sright.bcard.user.dal.entity.AdminDO;
import com.sright.bcard.user.dal.entity.MemberDO;
import com.sright.bcard.user.share.service.AuthService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author peter
 * @description
 * @date 2020/6/2
 */
@Component
@Slf4j
public class EnterpriseManagerImpl implements EnterpriseManager {

    @Value("${OPEN_ACCOUNT_SMS_TMP_CODE}")
    private String smsTmpCode;

    @Autowired
    private AdminDAO adminDAO;

    @Autowired
    private EnterpriseDAO enterpriseDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private CardUserCompanyInfoDAO cardUserCompanyInfoDAO;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private CardBaseInfoDAO cardBaseInfoDAO;

    @Autowired
    private MaterialDAO materialDAO;

    @Autowired
    private DingTalkManager dingTalkManager;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ContentCheckManager contentCheckManager;

    @Autowired
    private AuthService authService;

    @Override
    public EnterpriseDTO getEnterpriseDTO(Long enterpriseId) {
        if (enterpriseId == null) {
            return null;
        }
        EnterpriseDO enterpriseDO = enterpriseDAO.selectById(enterpriseId);
        EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
        BeanUtils.copyProperties(enterpriseDO, enterpriseDTO);
        // 设置企业名片开通总数
        List<UserDO> userDOS = userDAO.selectByEnterpriseId(enterpriseId);
        if(CollectionUtils.isNotEmpty(userDOS)) {
            List<UserDO> collect = userDOS.stream().filter(data -> data.getStatus() == 1).collect(Collectors.toList());
            enterpriseDTO.setTotal(CollectionUtils.isNotEmpty(collect) ? collect.size() : 0);
        } else {
            enterpriseDTO.setTotal(0);
        }
        return enterpriseDTO;
    }

    @Override
    public EnterpriseDTO getEnterprise(LoginUser loginUser) {
        Long adminId = loginUser.getUserId();
        if (adminId == null) {
            throw new BusinessErrorException(BusinessCode.NEED_LOGIN);
        }
        AdminDO adminDO = adminDAO.selectById(adminId);
        if (adminDO == null || adminDO.getEnterpriseId() == null) {
            throw new BusinessErrorException(BusinessCode.ENTERPRISE_NOT_EXIST);
        }
        EnterpriseDO enterpriseDO = enterpriseDAO.selectById(adminDO.getEnterpriseId());
        // DO 转 DTO
        EnterpriseDTO enterpriseDTO = DataConvertUtils.convertDO2DTO(enterpriseDO, EnterpriseDTO.class);
        enterpriseDTO.setUsername(adminDO.getUsername());
        // 设置企业名片开通总数
        List<UserDO> userDOS = userDAO.selectByEnterpriseId(loginUser.getEnterpriseId());
        if(CollectionUtils.isNotEmpty(userDOS)) {
            List<UserDO> collect = userDOS.stream().filter(data -> data.getStatus() == 1).collect(Collectors.toList());
            enterpriseDTO.setTotal(CollectionUtils.isNotEmpty(collect) ? collect.size() : 0);
        } else {
            enterpriseDTO.setTotal(0);
        }
        return enterpriseDTO;
    }

    @Override
    public Boolean updateEnterpriseInfo(UpdateEnterpriseParam param) {
        //新增敏感词审核
        List<String> contentList = new LinkedList<>();
        if (StringUtils.isNotEmpty(param.getCompany())) {
            contentList.add(param.getCompany());
        }
        if (StringUtils.isNotEmpty(param.getContacts())) {
            contentList.add(param.getContacts());
        }
        if (StringUtils.isNotEmpty(param.getDepartment())) {
            contentList.add(param.getDepartment());
        }
        if (CollectionUtils.isNotEmpty(contentList)) {
            String checkResult = contentCheckManager.textCheck(contentList,param.getEnterpriseId(), SourceTypeEnum.ENTERPRISE_BACKEND.getValue());
            if (checkResult.equals("block")) {
                throw new BusinessErrorException(BusinessCode.CONTAIN_SENSITIVE_WORDS);
            }
        }

        Long adminId = param.getUserId();
        if (adminId == null) {
            throw new BusinessErrorException(BusinessCode.NEED_LOGIN);
        }
        AdminDO adminDO = adminDAO.selectById(adminId);
        if (adminDO == null || adminDO.getEnterpriseId() == null) {
            throw new BusinessErrorException(BusinessCode.ENTERPRISE_NOT_EXIST);
        }
        EnterpriseDO enterpriseDO = new EnterpriseDO();
        enterpriseDO.setId(adminDO.getEnterpriseId());
        enterpriseDO.setName(param.getCompany());
        enterpriseDO.setContacts(param.getContacts());
        enterpriseDO.setMobile(param.getMobile());
        enterpriseDO.setDepartment(param.getDepartment());
        return enterpriseDAO.updateSelective(enterpriseDO);
    }

    @Override
    public EnterpriseDTO enterpriseInfo(Long enterpriseId) {
        // 获取企业id
        EnterpriseDO enterpriseDO = enterpriseDAO.selectById(enterpriseId);
        if(null == enterpriseDO) {
            return null;
        }
        EnterpriseDTO enterpriseDTO = DataConvertUtils.convertDO2DTO(enterpriseDO, EnterpriseDTO.class);
        //获取当前已绑定用户数量
        Long bindNum = userDAO.selectBindUserNumById(enterpriseId);
        enterpriseDTO.setBindedUserNum(bindNum);

        //获取所有已创建的用户数量
        Long createdNum = userDAO.selectCreatedUserNum(enterpriseId);
        enterpriseDTO.setCreatedUserNum(createdNum);
        return enterpriseDTO;
    }

    @Override
    public List<EnterpriseDTO> getEnterpriseList() {
        List<EnterpriseDO> doList = enterpriseDAO.selectEnterpriseList();
        List<EnterpriseDTO> dtoList = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(doList, dtoList, EnterpriseDTO.class);
        return dtoList;
    }

    @Override
    public Boolean updateEnterprise(EnterpriseDTO enterpriseDTO) throws ParseException {
        if (StringUtils.isNotEmpty(enterpriseDTO.getName())) {
            List<String> contentList = new LinkedList<>();
            contentList.add(enterpriseDTO.getName());
            String checkResult = contentCheckManager.textCheck(contentList,enterpriseDTO.getId(), SourceTypeEnum.ENTERPRISE_BACKEND.getValue());
            if (checkResult.equals("block")) {
                throw new BusinessErrorException(BusinessCode.CONTAIN_SENSITIVE_WORDS);
            }
        }
        EnterpriseDO enterpriseDO = new EnterpriseDO();
        DataConvertUtils.convertDTO2DO(enterpriseDTO, enterpriseDO);
        Long expirationAt = enterpriseDTO.getExpiration_at();
        String s = DateTimeUtils.longTransStringDate(expirationAt * 1000);
        Date date = DateTimeUtils.formateTimeStart(s);
        enterpriseDO.setExpirationAt(date);
        return enterpriseDAO.updateSelective(enterpriseDO);
    }

    @Override
    public Pager<EnterpriseMemberDTO> enterpriseMember(Integer page, Integer pageSize, String keywords, Long enterpriseId) {

        if (StringUtils.isEmpty(keywords)) {
            keywords = null;
        }
        PageParamRequest paramRequest = new PageParamRequest();
        Integer offset = (page - 1) * pageSize;
        paramRequest.setOffset(offset);
        paramRequest.setLimit(pageSize);

        Integer count = userDAO.selectUserCountByEnterpriseId(enterpriseId, keywords);
        List<EnterpriseMemberResult> enterpriseMemberResults = userDAO.selectUserInfoByEnterpriseId(enterpriseId, keywords, paramRequest);
        //获取企业公共背景图
        List<CardListDTO> cardList = cardDAO.selectIdListByEnterpriseId(enterpriseId);
        String background = "";
        if (CollectionUtils.isNotEmpty(cardList)) {
            CardDO cardDO = cardDAO.selectById(cardList.get(0).getId());
            CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
            if (cardBaseInfoDO != null && !cardBaseInfoDO.getMaterialIds().equals("")) {
                String[] materialIds = cardBaseInfoDO.getMaterialIds().split(",");
                List<Long> materialIdList = new ArrayList<>();
                for(String materialId : materialIds) {
                    materialIdList.add(Long.valueOf(materialId));
                }
                if (materialIds.length > 0) {
                    List<MaterialDO> materialDOList = materialDAO.selectByMaterialIdList(materialIdList);
                    if (materialDOList != null && materialDOList.size() > 0) {
                        List<Long> typeList = Arrays.asList(1L,2L,4L,5L);
                        for (MaterialDO materialDO : materialDOList) {
                            if (typeList.contains(cardBaseInfoDO.getTemplateId())) {
                                if (materialDO.getType() == 1 || materialDO.getType() == 2) {
                                    background = materialDO.getFilePath();
                                }
                            } else {
                                if (materialDO.getType() == 6) {
                                    background = materialDO.getFilePath();
                                }
                            }
                        }
                    }
                }
            }
        }

        List<EnterpriseMemberDTO> dtoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(enterpriseMemberResults)) {
            for (EnterpriseMemberResult enterpriseMemberResult : enterpriseMemberResults) {
                EnterpriseMemberDTO enterpriseMemberDTO = new EnterpriseMemberDTO();
                enterpriseMemberDTO.setUserId(enterpriseMemberResult.getUserId());
                enterpriseMemberDTO.setNameZh(enterpriseMemberResult.getName());
                enterpriseMemberDTO.setMobile(enterpriseMemberResult.getMobile());
                enterpriseMemberDTO.setFilePath("");
                if (background.equals("")) {
                    //没有公共就取个人
                    CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectByUserId(enterpriseMemberResult.getUserId());
                    if (cardBaseInfoDO != null) {
                        if (!cardBaseInfoDO.getMaterialIds().equals("")) {
                            String[] materialIds = cardBaseInfoDO.getMaterialIds().split(",");
                            List<Long> materialIdList = new ArrayList<>();
                            for(String materialId : materialIds) {
                                materialIdList.add(Long.valueOf(materialId));
                            }
                            if (materialIds.length > 0) {
                                List<MaterialDO> materialDOList = materialDAO.selectByMaterialIdList(materialIdList);
                                if (materialDOList != null && materialDOList.size() > 0) {
                                    List<Long> typeList = Arrays.asList(1L,2L,4L,5L);
                                    for (MaterialDO materialDO : materialDOList) {
                                        if (typeList.contains(cardBaseInfoDO.getTemplateId())) {
                                            if (materialDO.getType() == 1 || materialDO.getType() == 2) {
                                                enterpriseMemberDTO.setFilePath(materialDO.getFilePath());
                                                background = materialDO.getFilePath();
                                            }
                                        } else {
                                            if (materialDO.getType() == 6) {
                                                enterpriseMemberDTO.setFilePath(materialDO.getFilePath());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    enterpriseMemberDTO.setFilePath(background);
                }

                //获取logo（9.7日需求变动，因与通讯录显示不一致，不再显示logo，显示头像）
//                List<MaterialDO> logoList = materialDAO.selectByUserIdAndType(enterpriseMemberResult.getUserId(), MaterialTypeEnum.LOGO.getValue());
//                if (CollectionUtils.isNotEmpty(logoList)) {
//                    enterpriseMemberDTO.setLogo(logoList.get(0).getFilePath());
//                } else {
//                    enterpriseMemberDTO.setLogo("");
//                }

                MemberDO memberDO = memberDAO.selectById(enterpriseMemberResult.getMemberId());
                if (memberDO != null) {
                    enterpriseMemberDTO.setLogo(memberDO.getAvatarLocal());
                } else {
                    enterpriseMemberDTO.setLogo("");
                }

                //获取公司职位信息
                List<CardUserCompanyInfoDO> companyInfoDOList = cardUserCompanyInfoDAO.selectByCardUserInfoId(enterpriseMemberResult.getId());
                if (CollectionUtils.isNotEmpty(companyInfoDOList)) {
                    enterpriseMemberDTO.setDepartmentName(companyInfoDOList.get(0).getDepartment());
                    enterpriseMemberDTO.setJobName(companyInfoDOList.get(0).getJob());
                } else {
                    enterpriseMemberDTO.setDepartmentName("");
                    enterpriseMemberDTO.setJobName("");
                }

                dtoList.add(enterpriseMemberDTO);
            }
        }

        Pager pager = new Pager(page, pageSize, count, dtoList);
        return pager;
    }

    @Override
    public void pushExpireEnterprise() {
        String content = "Cuface企业账号\r";
        boolean isPush = false;

        String seven = getExpireEnterpriseListString(7);
        if (seven.length() > 1) {
            isPush = true;
            content = content + seven + "\r";
        }

        String three = getExpireEnterpriseListString(3);
        if (three.length() > 1) {
            isPush = true;
            content = content + three + "\r";
        }

        String one = getExpireEnterpriseListString(1);
        if (one.length() > 1) {
            isPush = true;
            content = content + one + "\r";
        }

        if (isPush) {
            //进行钉钉推送
            try {
                dingTalkManager.sendGroupMessage(content);
            } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
                log.info("钉钉推送失败 : {}", e.getMessage());
            } catch (ApiException e) {
                log.info("钉钉推送失败 : {}", e.getErrMsg());
                e.printStackTrace();
            }
        }
    }

    @Override
    public Integer onStatus(EnterpriseDTO enterpriseDTO) {
        EnterpriseDO enterpriseDO = new EnterpriseDO();
        enterpriseDO.setId(enterpriseDTO.getEnterpriseId());
        enterpriseDO.setIsOpen(enterpriseDTO.getIsOpen());
        return enterpriseDAO.onStatus(enterpriseDO);
    }

    @Override
    public void pushEnterpriseOpen() {
        //获取到期还有十天的客户
        String beginTimeString = DateTimeUtils.getAfterDay(10);
        String endTimeString = DateTimeUtils.getAfterDay(11);

        Date beginDate = DateTimeUtils.formatDate(beginTimeString,DateTimeUtils.DATE_TIME_STYLE);
        Date endDate = DateTimeUtils.formatDate(endTimeString,DateTimeUtils.DATE_TIME_STYLE);

        List<EnterpriseDO> enterpriseDOList = enterpriseDAO.selectExpireListByCreateDate(beginDate,endDate);

        OpenAccountMessageDTO openAccountMessageDTO = new OpenAccountMessageDTO();
        openAccountMessageDTO.setNum(10);
        String jsonParam = JSON.toJSONString(openAccountMessageDTO);
        if (CollectionUtils.isNotEmpty(enterpriseDOList)) {
            for (EnterpriseDO enterpriseDO : enterpriseDOList) {
                try {
                    smsService.sendMessage(jsonParam,smsTmpCode,enterpriseDO.getMobile());
                    log.info("短信发送成功，接收人 : {}", enterpriseDO.getMobile());
                } catch (ClientException e) {
                    log.info("短信发送失败 : {}", e.getErrMsg());
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void createAccount(CreateAccountParam param) {
        RegisterDTO registerDTO = new RegisterDTO();
        registerDTO.setUsername(param.getMobile());
        registerDTO.setName(param.getCompany());
        registerDTO.setPassword(param.getMobile());
        registerDTO.setContacts(param.getContacts());
        registerDTO.setMobile(param.getMobile());
        registerDTO.setDays(param.getDays());
        registerDTO.setExpirationAt(new Date(param.getExpirationAt() * 1000));
        registerDTO.setCardCoverLimit(param.getCardCoverLimit());
        registerDTO.setCardLogoLimit(param.getCardLogoLimit());
        registerDTO.setCardLogoLimit(param.getCardLogoLimit());
        registerDTO.setVideoCoverLimit(param.getVideoCoverLimit());
        registerDTO.setCorporateVideoLimit(param.getCorporateVideoLimit());
        registerDTO.setCardNum(param.getCardNum());
        try {
            authService.register(registerDTO);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    protected String getExpireEnterpriseListString(Integer day) {
        String beginTimeString = DateTimeUtils.getAfterDay(day);
        String endTimeString = DateTimeUtils.getAfterDay(day + 1);

        Date beginDate = DateTimeUtils.formatDate(beginTimeString,DateTimeUtils.DATE_TIME_STYLE);
        Date endDate = DateTimeUtils.formatDate(endTimeString,DateTimeUtils.DATE_TIME_STYLE);

        List<EnterpriseDO> enterpriseDOList = enterpriseDAO.selectExpireListByDate(beginDate,endDate);

        String result = "";
        if (CollectionUtils.isNotEmpty(enterpriseDOList)) {
            for (EnterpriseDO enterpriseDO : enterpriseDOList) {
                result = result + enterpriseDO.getName() + "、";
            }
            result = result.substring(0,result.length()-1);
            result += "还有" + day + "天到期";
        }

        return result;
    }
}
